<template>
  <div class="home-container">
    <!-- 头部 -->
    <div class="top-box">
      <div class="left">
        <img
          v-if="UserForm.avatar"
          :src="`http://127.0.0.1:8000${UserForm.avatar}`"
          alt=""
          style="width: 100px; height: 100px; border-radius: 75px"
        />
        <img
          v-else
          src="@/assets/imgs/默认头像.png"
          alt=""
          style="width: 100px; height: 100px; border-radius: 75px"
        />
        <div>
          <h1>你好~{{ userdata.username }}</h1>
          <p @click="editAvatar" style="cursor: pointer">
            <i class="el-icon-edit"></i>修改头像
          </p>
        </div>
      </div>

      <el-button type="warning" @click="logout">退出登录</el-button>
    </div>
    <!-- 收藏与设计方案 -->
    <div class="seconde-box">
      <img
        src="@/assets/imgs/我的收藏.png"
        alt=""
        style="border-radius: 5px; margin-right: 140px"
        @click="goCollect"
      />
      <img
        src="@/assets/imgs/我的设计方案.png"
        alt=""
        style="border-radius: 5px"
        @click="goDesign"
      />
    </div>
    <!-- 账户信息，修改密码 -->
    <div class="userInfo">
      <div class="btns">
        <div
          class="title"
          :class="{ highlighted: showAccount }"
          style="margin-right: 200px"
        >
          <h2 @click="showAccountForm">账户信息</h2>
        </div>
        <div class="title" :class="{ highlighted: showPassword }">
          <h2 @click="showPasswordForm">修改密码</h2>
        </div>
      </div>
      <!-- 账户信息 -->
      <div class="form-box" v-if="showAccount">
        <div class="form" style="text-align: center">
          <el-form
            ref="UserForm"
            :model="UserForm"
            label-width="120px"
            style="display: inline-block; margin-top: 100px"
          >
            <el-form-item label="用户名:" class="">
              <el-input
                v-model="UserForm.username"
                style="width: 300px"
                placeholder="请输入用户名"
              ></el-input>
            </el-form-item>
            <el-form-item label="手机号:">
              <el-input
                v-model="UserForm.phone"
                style="width: 300px"
                placeholder="请输入手机号"
              ></el-input>
            </el-form-item>
            <el-form-item label="邮箱:">
              <el-input
                v-model="UserForm.email"
                style="width: 300px"
                placeholder="请输入邮箱"
              ></el-input>
            </el-form-item>
          </el-form>
          <div>
            <el-button style="margin-top: 10px" type="success" @click="eidtinfo"
              >修改信息</el-button
            >
          </div>
        </div>
      </div>
      <!-- 修改密码 -->
      <div class="form-box" v-if="showPassword">
        <div class="form" style="text-align: center">
          <el-form
            ref="passwordForm"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="190px"
            style="display: inline-block; margin-top: 100px"
          >
            <el-form-item label="旧密码:" prop="current_password">
              <el-input
                v-model="passwordForm.current_password"
                style="width: 300px"
                placeholder="请输入旧密码"
              ></el-input>
            </el-form-item>
            <el-form-item label="新密码:" prop="new_password">
              <el-input
                v-model="passwordForm.new_password"
                style="width: 300px"
                placeholder="请输入新密码"
              ></el-input>
            </el-form-item>
            <el-form-item label="确认新密码:" prop="confirm_password">
              <el-input
                v-model="passwordForm.confirm_password"
                style="width: 300px"
                placeholder="请再次输入新密码"
              ></el-input>
            </el-form-item>
          </el-form>
          <div>
            <el-button
              style="margin-top: 10px"
              type="success"
              @click="editpassword"
              >修改密码</el-button
            >
          </div>
        </div>
      </div>
    </div>
    <!-- 底部 -->
    <Footer />
    <!-- 修改头像弹窗 -->
    <div>
      <el-dialog title="修改头像" :visible.sync="Avatardialog" width="30%">
        <el-form
          :model="AvatarForm"
          :inline="true"
          class="visible"
          label-width="120px"
          ref="AvatarForm"
        >
          <!-- 图片上传组件 -->
          <el-form-item label="图片">
            <el-upload
              action="#"
              list-type="picture-card"
              :file-list="fileList"
              :limit="1"
              :on-exceed="handleExceed"
              :on-change="beforeUploadone"
              @remove="handleRemove"
              :auto-upload="false"
              ref="upload"
            >
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{ file }">
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                  alt=""
                />
                <span class="el-upload-list__item-actions">
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="validation">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { Message } from "element-ui";
import Cookies from "js-cookie";
import { userLogout, updatapwd } from "@/api/login.js";
import { getuser, putuser } from "@/api/user.js";
import { mapActions, mapState } from "vuex";
import Footer from "../components/footer.vue";
export default {
  components: {
    Footer,
  },
  name: "homePage",
  data() {
    return {
      userdata: {
        username: "",
        avatar: "",
      },
      showAccount: true, //账户信息
      showPassword: false, //修改密码
      Avatardialog: false, //修改头像弹出
      disabled: false, //图片删除
      file: null, // 用户选择的图片
      fileList: [], // 文件列表
      UserForm: {
        username: "",
        phone: "",
        email: "",
      },
      AvatarForm: {
        avatar: "",
      }, //头像表单
      //密码表单
      passwordForm: {
        current_password: "",
        new_password: "",
        confirm_password: "",
      },
      // 验证规则
      passwordRules: {
        current_password: [
          { required: true, message: "请输入正确的旧密码", trigger: "blur" },
        ],
        new_password: [
          { required: true, message: "请输入新密码", trigger: "blur" },
        ],
        confirm_password: [
          { required: true, message: "请再次输入新密码", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  created() {
    this.userdata.username = this.user.username;
    this.getUserInfo();
  },
  methods: {
    ...mapActions(["resetState", "updateUser"]), //清空vuex,修改数据
    // 获取用户信息
    getUserInfo() {
      getuser(this.user.id)
        .then((res) => {
          console.log(res);
          this.UserForm = res.results;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 表单切换(账户信息)
    showAccountForm() {
      this.showAccount = true;
      this.showPassword = false;
    },
    // 表单切换(修改密码)
    showPasswordForm() {
      this.showAccount = false;
      this.showPassword = true;
    },
    // 修改头像弹窗显示
    editAvatar() {
      this.Avatardialog = true;
    },
    handleExceed() {
      this.$message.warning("当前限制选择 1 个文件");
    },
    beforeUploadone(file) {
      this.file = file.raw;
      console.log(this.file);
      return false;
    },
    handleRemove(file) {
      console.log(file);
      this.file = null;
      this.fileList = [];
    },

    validation() {
      this.$refs["AvatarForm"].validate((valid) => {
        if (valid) {
          let formData = new FormData();
          formData.append("avatar", this.file);
          console.log(formData);
          putuser(this.user.id, formData)
            .then((res) => {
              this.$message.success("修改成功");
              this.Avatardialog = false;
              this.$refs.upload.clearFiles();
              this.getUserInfo();
            })
            .catch((err) => {
              this.$message.error("数据格式错误");
            });
        } else {
          this.$message.error("数据格式错误");
          return false;
        }
      });
    },
    cancel() {
      this.Avatardialog = false;
      this.$refs.upload.clearFiles();
    },
    // 收藏页
    goCollect() {
      this.$router.push({
        path: "/collect",
      });
    },
    // 设计方案
    goDesign() {
      this.$router.push({
        path: "/designScheme",
      });
    },
    // 修改账户信息
    eidtinfo() {
      const payload = {
        username: this.UserForm.username,
        phone: this.UserForm.phone,
        email: this.UserForm.email,
      };
      putuser(this.user.id, payload)
        .then((res) => {
          console.log(res);
          if (res.message == "用户信息更新成功") {
            this.updateUser(res.results);
            this.getUserInfo();
            Message({
              message: "修改成功",
              type: "success",
            });
            // 刷新页面
            window.location.reload();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 修改密码
    editpassword() {
      this.$refs.passwordForm.validate((valid) => {
        if (valid) {
          updatapwd(this.user.id, this.passwordForm)
            .then((res) => {
              console.log(res);
              // 提示
              Message({
                message: "修改成功",
                type: "success",
              });
              // 修改密码成功后，退出登录
              this.logout();
            })
            .catch((err) => {
              console.log(err);
            });
        }
      });
    },
    // 退出登录
    logout() {
      userLogout().then((res) => {
        if (res.message == "您已成功注销。") {
          localStorage.removeItem("vuex");
          Cookies.remove("token");
          this.resetState(); // 清空vuex状态
          this.$router.push("/");
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.home-container {
  .top-box {
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    margin-top: 30px;
    .left {
      display: flex;
      align-items: center;
      margin-right: 180px;
      img {
        margin-right: 25px;
      }
      p {
        margin-top: 10px;
        color: #aaaaaa;
      }
    }
  }
  .seconde-box {
    margin-top: 30px;
    display: flex;
    justify-content: center;
    img {
      cursor: pointer;
    }
  }
  .third-box {
    margin-top: 30px;
    display: flex;
    justify-content: center;
    img {
      // 小手
      cursor: pointer;
    }
  }
  .fourth-box {
    margin-top: 30px;
    display: flex;
    justify-content: center;
    img {
      // 小手
      cursor: pointer;
    }
  }
  .userInfo {
    .btns {
      margin-top: 50px;
      display: flex;
      justify-content: center;
      .title {
        width: 380px;
        border-bottom: 3px solid #333333;
        // 触碰时变小手
        cursor: pointer;
      }
      .highlighted {
        color: #d4840e; /* 设置高亮颜色 */
        border-bottom-color: #d4840e;
      }
    }
    .form-box {
      width: 990px;
      height: 430px;
      margin: 50px auto;
      background-color: #f9d092;
      border-radius: 10px;
      .el-form-item {
        margin-bottom: 40px;
      }
      /deep/ .el-form-item__label {
        font-size: 26px;
        color: #333333;
      }
    }
  }
}
</style>
